$(function () {
    //获取token
    var token = localStorage.token;
    if (!token) {
        location.href = "../loginAndReg/login.html";
    };
    //获取购物车列表
    $.ajax({
        type: "get",
        url: domain.test + "/getcarlist",
        async: false,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("token", token);
        },
        success: function (response) {
            if (response.data.rtnCode === 200) {
                var carList = response.data.data;
                console.log(carList);
                $(".carList").html(template("carList", { carList: carList }));
                $(".emptyCarBox").html(template("emptyCarBox", { length: carList.length }));
                if (carList.length === 0) {
                    window.hasStatus = true;
                    $(".layout").css("margin-bottom", 0);
                }
            }
            if (response.data.rtnCode === 401) {
                var outTimeCode = response.data.rtnCode;
                location.href = "../../index.html?outTimeCode=" + outTimeCode;
            }
        }
    });
    //列表左右滑动
    var startX, animateX, endX;
    $(".carList").on("touchstart", ".scrollBox", function (e) {
        startX = e.changedTouches[0].clientX;
    });
    $(".carList").on("touchmove", ".scrollBox", function (e) {
        animateX = e.changedTouches[0].clientX;
    });
    $(".carList").on("touchend", ".scrollBox", function (e) {
        endX = e.changedTouches[0].clientX;
        if (Math.abs(startX - endX) > 10) {
            var temp = parseFloat($(".functionBtn").css("width"));
            if (startX - endX > 0) {
                var left = parseFloat($(this).css("left"));
                if (left === 0) {
                    $(".scrollBox").animate({
                        "left": 0
                    });
                    $(this).animate({
                        "left": -temp
                    }, 300);
                }

            }
            if (startX - endX < 0) {
                var left = parseFloat($(this).css("left"));
                if (left === -temp) {
                    $(this).animate({
                        "left": 0
                    }, 300);
                }
            }
        }
    });
    //删除购物车
    $(".carList").on("click", ".delBtn", function () {
        var id = parseInt($(this).attr("data-id"));
        console.log(id);
        $.ajax({
            type: "delete",
            url: domain.test + `/delcar?id=${id}`,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("token", token);
            },
            success: function (response) {
                console.log(response);
                if (response.data.rtnCode === 200) {
                    location.reload();
                }
            }
        });
    });
    //购物车数量增减
    var totalPrice = 0;
    var totalNum = 0;
    function addOrCutCar(ele, id, count) {
        $.ajax({
            type: "put",
            url: domain.test + "/addorcutcar",
            data: {
                id: id,
                count: count
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("token", token);
            },
            success: function (response) {
                if (response.data.rtnCode === 200) {
                    ele.parent().parent().parent().find(".pNum").html(count);
                    ele.parent().parent().parent().find(".num").html(count);
                    var status = parseInt(ele.parent().parent().parent().find(".select").val());
                    var tempPrice = parseFloat(ele.parent().parent().parent().find(".monney").attr("data-sprice"));
                    if (status === 1) {
                        if (ele.hasClass("cut")) {
                            totalNum -= 1;
                            totalPrice -= tempPrice * 1;
                            $(".tNum").html(totalNum);
                            $(".tMoney").html(totalPrice.toFixed(2));
                        }
                        if (ele.hasClass("add")) {
                            totalNum += 1;
                            totalPrice += tempPrice * 1;
                            $(".tNum").html(totalNum);
                            $(".tMoney").html(totalPrice.toFixed(2));
                        }
                    }
                }
                if (response.data.rtnCode === 400) {
                    alert(response.data.msg);
                }
            }
        });
    }
    $(".carList").on("click", ".add", function () {
        var _this = $(this);
        var num = parseInt($(this).parent().parent().parent().find(".num").html());
        var id = parseInt($(this).attr("data-id"));
        addOrCutCar(_this, id, num + 1);
    });
    $(".carList").on("click", ".cut", function () {
        var _this = $(this);
        var num = parseInt($(this).parent().parent().parent().find(".num").html());
        if (num === 1) return false;
        var id = parseInt($(this).attr("data-id"));
        addOrCutCar(_this, id, num - 1);
    });
    //购物车商品是否选中
    $(".carList").on("click", ".lable", function () {
        var value = parseInt($(this).parent().find(".select").val());
        if (value === 0) {
            $(this).parent().find(".select").val(1);
            $(this).find("img").attr("src", "../../static/img/ico_select@3x.png");
            //选中商品，获取商品数量和单价
            var pNum = parseInt($(this).parent().parent().find(".pNum").html());
            var sPrice = parseFloat($(this).parent().parent().find(".monney").attr("data-sprice"));
            totalPrice += pNum * sPrice;
            console.log(totalPrice);
            watchPrice(totalPrice);
            totalNum += pNum;
            $(".tMoney").html(totalPrice.toFixed(2));
            $(".tNum").html(totalNum);
            eachElement();
        } else if (value === 1) {
            $(this).parent().find(".select").val(0);
            $(this).find("img").attr("src", "../../static/img/ico_selectk@3x.png");
            var pNum = parseInt($(this).parent().parent().find(".pNum").html());
            var sPrice = parseFloat($(this).parent().parent().find(".monney").attr("data-sprice"));
            // console.log(pNum,sPrice,totalPrice);
            console.log(totalPrice);
            // totalPrice -= pNum * sPrice;
            totalPrice = parseFloat(totalPrice.toFixed(2)) - pNum * sPrice;
            console.log(totalPrice);
            watchPrice(totalPrice);
            totalNum -= pNum;
            $(".tMoney").html(totalPrice.toFixed(2));
            $(".tNum").html(totalNum);
            eachElement();
        }
    });
    //是否全选
    $(".carList").on("click", ".selectAllLable", function () {
        var value = parseInt($(this).parent().find(".selectAll").val());
        if (value === 0) {
            $(this).parent().find(".selectAll").val(1);
            $(this).find("img").attr("src", "../../static/img/ico_select@3x.png");
            var allTNum = 0;
            var allTPrice = 0;
            $.each($(".lable"), function (index, ele) {
                $(ele).parent().find(".select").val(1);
                $(ele).find("img").attr("src", "../../static/img/ico_select@3x.png");
                var aNum = parseInt($(ele).parent().parent().find(".pNum").html());
                var aPrice = parseFloat($(ele).parent().parent().find(".monney").attr("data-sprice"));
                allTPrice += aPrice * aNum;
                allTNum += aNum;

            });
            totalPrice = allTPrice;
            console.log(totalPrice);
            watchPrice(totalPrice);
            totalNum = allTNum;
            $(".tMoney").html(totalPrice.toFixed(2));
            $(".tNum").html(totalNum);
        } else if (value === 1) {
            $(this).parent().find(".selectAll").val(0);
            $(this).find("img").attr("src", "../../static/img/ico_selectk@3x.png");
            $.each($(".lable"), function (index, ele) {
                $(ele).parent().find(".select").val(0);
                $(ele).find("img").attr("src", "../../static/img/ico_selectk@3x.png");
            });
            $(".tMoney").html("0.00");
            $(".tNum").html(0);
            $(".rightPart").css("background-color", "#999");
            $(".rightPart").attr("data-paystatus", 0);
        }
    });
    function eachElement() {
        $.each($(".lable"), function (index, element) {
            if (parseInt($(element).parent().find(".select").val()) === 0) {
                $(".selectAll").val(0);
                $(".selectAllLable").find("img").attr("src", "../../static/img/ico_selectk@3x.png");
                return false;
            } else {
                $(".selectAll").val(1);
                $(".selectAllLable").find("img").attr("src", "../../static/img/ico_select@3x.png");
            }
        });
    }
    //监视选中商品的总价
    function watchPrice(totalPrice) {
        if (totalPrice === 0) {
            $(".rightPart").css("background-color", "#999");
            $(".rightPart").attr("data-paystatus", 0);
        }
        if (totalPrice > 0) {
            $(".rightPart").css("background-color", "#212121");
            $(".rightPart").attr("data-paystatus", 1);
        }
    }
    //结算
    $(".carList").on("click", ".rightPart", function () {
        var payStatus = parseInt($(this).attr("data-paystatus"));
        if(payStatus===0) {
            return false;
        }
        if(payStatus===1) {
            var productObj = [];
            $.each($(".select"),function(index,element) {
                if(parseInt($(element).val())===1) {
                    console.log(9999);
                    var productItem = {};
                    productItem.img = $(element).parent().parent().find(".carImg img").attr("src");
                    productItem.productName = $(element).parent().parent().find(".productName").html();
                    productItem.sku = $(element).parent().parent().find(".size").html();
                    productItem.price = parseFloat($(element).parent().parent().find(".monney").attr("data-sprice")).toFixed(2);
                    productItem.diamond = parseFloat($(element).parent().parent().find(".diamond").attr("data-diamond")).toFixed(2);
                    productItem.cash = parseFloat($(element).parent().parent().find(".cash").attr("data-cash")).toFixed(2);
                    productItem.count = $(element).parent().parent().find(".pNum").html();                      
                    productObj.push(productItem);
                }
            });
            localStorage.sureOrderProductDetail = JSON.stringify(productObj);
            console.log(totalPrice);
            localStorage.totalPrice = totalPrice.toFixed(2);
            console.log(JSON.parse(localStorage.sureOrderProductDetail));
            location.href = "./sureOrder.html";
        }
    });
    //猜你喜欢
    var flag = false;
    var pageNum = 1;
    function loadLikeProduct() {
        if (flag) return false;
        $.ajax({
            url: domain.test + "/getlike",
            // url: domain.online + "/api/index/like",
            type: 'get',
            data: 'pageNum=' + pageNum,
            dataType: 'json',
            beforeSend: function () {
                flag = true;
            },
            success: function (response) {
                var likeProductDetail = response.data.data;
                // var likeProductDetail = response.data;
                if (pageNum == 1) {
                    $('.itemBox').html(template('itemBox', { productList: likeProductDetail.plist }));
                } else {
                    $('.itemBox').append(template('itemBox', { productList: likeProductDetail.plist }));
                }
                pullmaster.pullDownSuccess();       //刷新成功
                if (likeProductDetail.plist.length < 10 || likeProductDetail.plist.length === 0) {
                    pullmaster.pullUpDone();        //到底啦
                    $(".bb_pull-up").css({ "display": "none" });
                    $(".end").css({ "display": "block" });
                }
                ++pageNum;
                flag = false;
            },
            error: function () {
                pullmaster.pullDownFailed();        //刷新失败
                pullmaster.pullUpFailed();          //数据加载失败
            }
        })
    }
    // 下拉刷新上滑分页加载
    if (window.hasStatus) {
        $(".likeIcon").css("display", "block");
        var pullmaster = new Pull($('.likeProduct'), {
            onPullUp: function () {
                loadLikeProduct();
            },
            onPullDown: function () {
                pageNum = 1;
                loadLikeProduct();
            }
        });
    }
    //查看详情
    $(".itemBox").on("click", ".likeProductItem", function () {
        var pId = $(this).attr("data-id");
        location.href = "../classify/product.html?id=" + pId;
    })
})